import { useEffect, useState } from 'react';
import { Button, View, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import NavBar from '@/components/NavBar';
import { registerUser } from '@/service/apis/session';
import { setToken } from '@/utils/authUtil';
import logoIcon from '@/assets/images/user/logo.png';

import './index.scss';

let code = '';
/**
 * 设置页面
 * @returns
 */
const Login = ({ onLoginSuccess, showBackBtn }) => {
  const [isChecked, setIschecked] = useState(true);
  const agreementList = [
    {
      title: '趣驿站用户协议',
      path: '/subPages/agreement/index?type=register',
    },
    {
      title: '趣驿站隐私政策',
      path: '/subPages/agreement/index?type=privacy',
    },
  ];

  useEffect(() => {
    // 缓存code。
    Taro.login({
      success: (res) => {
        console.log('res', res);
        code = res.code;
      },
    });
  }, []);

  const getPhoneNumber = async (e) => {
    console.log(e);
    if (e.detail.errMsg.indexOf('user deny') > -1) {
      return Taro.showToast({
        title: '请允许授权手机号',
        icon: 'none',
      });
    }
    // 注册获取用户手机号。
    try {
      const { data } = await registerUser({
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData,
        code,
      });
      console.log(data);
      if (data.token) {
        setToken(data.token);
        onLoginSuccess(data.token);
      } else {
        Taro.showToast({
          title: '缺失token',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error(err);
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  const showToast = () => {
    Taro.showToast({
      icon: 'none',
      title: '请先勾选以下协议',
    });
  };

  const toAgreement = (path: string) => {
    console.log(path);
    Taro.navigateTo({
      url: path,
    });
  };
  return (
    <View className="login-container page-container">
      <NavBar showBackBtn={showBackBtn} title="登录" style={{ color: '#333' }} />
      <View className="login-logo">
        <Image src={logoIcon} />
      </View>
      {isChecked ? (
        <Button className="login-btn" openType="getPhoneNumber" onGetPhoneNumber={getPhoneNumber}>
          <Text className="iconfont icon-weixin" />
          <Text className="login-text">微信快速登录</Text>
        </Button>
      ) : (
        <Button className="login-btn" onClick={showToast}>
          <Text className="iconfont icon-weixin" />
          <Text className="login-text">微信快速登录</Text>
        </Button>
      )}

      <View className="agreement-tips-wrap">
        <Text
          className={`login-check-icon iconfont ${isChecked ? 'icon-checked' : 'icon-unchecked'}`}
          onClick={() => setIschecked(!isChecked)}
        />
        <View className="agreement-tips">
          我已阅读并同意
          {agreementList.map((item, index) => {
            return (
              <View key={index} className="agreement-title" onClick={() => toAgreement(item.path)}>
                《{item.title}》{agreementList.length - 1 === index ? '' : ','}
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
};
export default Login;
